//引入axios 核心库
import axios from 'axios'
//引入querystring
import qsString from 'querystring'

import router from '../router'

let baseUrl = '/api'

//请求拦截器
axios.interceptors.request.use(req => {
    if (req.url == '/api/userlogin') {
        return req;
    } else {
        req.headers.authorization = sessionStorage.getItem('userinfo') ? JSON.parse(sessionStorage.getItem('userinfo')).token : null;

        return req
    }
})

//响应拦截器
axios.interceptors.response.use(res => {
    if (res.data.msg == '请设置请求头,并携带验证字符串') {
        router.push('/login')
    }
    if (res.data.msg == '登录已过期或访问权限受限') {
        router.push('/login')
    }
    return res.data
})

//封装get请求方法
export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        axios.get(baseUrl+url, { params })
            .then(res => resolve(res))
            .catch(err => reject(err))
    })
}

//封装post请求方法
export const post = (url, params = {}, isFile = false) => {
    let data = {}
    if (isFile) {
        data = new FormData()
        for (let i in params) {
            data.append(i,params[i])
        }
    } else {
        data = qsString.stringify(params)
    }
    return new Promise((resolve, reject) => {
        axios.post(baseUrl+url, data)
            .then(res => resolve(res))
            .catch(err => reject(err))
    })
}